package base.thread_demo.demo11;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 双线程间通信案例：打印出1-100，使用两个线程轮番打印输出
 * synchronized 版
 */
public class CommunicationDemo {
    public static void main(String[] args) {
        NumRunnable1 runnable1 = new NumRunnable1();
        new Thread(runnable1, "t1").start();
        new Thread(runnable1, "t2").start();
    }

}

class NumRunnable1 implements Runnable{
    private static final Logger log = LoggerFactory.getLogger(NumRunnable1.class);
    private int count=1;

    @Override
    public void run() {
        while (true){
            synchronized (this){
                this.notify();
                if(count <= 100) {
                    log.info("{}->{}", Thread.currentThread().getName(), count);
                    count++;
                    try {
                        //使得调用wait()方法的线程进入阻塞状态,一旦调用wait()方法，只有等到同步锁对象去
                        //调用notify()唤醒,所以在调用wait()方法前，记得一定要唤醒等待中的线程。
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    break;
                }
            }
        }
    }
}
